<template>
  <div class="work-flow">
    <iframe
      v-if="isDetails"
      class="work-flow__iframe"
      id="workflow"
      name="myOnlyViewFrame"
      frameborder="0"
      width="100%"
      ref="iframe"
      :src="iframeUrl"
    ></iframe>
    <iframe
      v-else
      class="work-flow__iframe"
      id="workflow"
      name="myFrame"
      frameborder="0"
      width="100%"
      ref="iframe"
      :src="iframeUrl"
    ></iframe>
    <dialogPublic
      :title="'信息选择'"
      :show.sync="showDialog"
      @doSubmit="addSeleteMember"
      @doClose="() => (showDialog = false)"
      :fullscreen="true"
      appendTobody
    >
      <newMemberSelect
        ref="newMember"
        v-if="showDialog"
        :seleteSetting="orgMemberSelect"
      ></newMemberSelect>
    </dialogPublic>
    <dialogPublic
      :title="'信息选择'"
      width="60%"
      :show.sync="showMember"
      @doSubmit="addSeleteMember"
      @doClose="() => (showMember = false)"
      appendTobody
    >
      <workFlowMember
        ref="newMember"
        v-if="showMember"
        :seleteSetting="orgMemberSelect"
      ></workFlowMember>
    </dialogPublic>
    <dialogPublic
      :title="'操作确认'"
      height="460px"
      :show.sync="showDetail"
      @doSubmit="commitAll"
      @doClose="() => (showDetail = false)"
      appendTobody
    >
      <div class="nextNode">
        <editForm
          :formConfig="formConfig"
          ref="nodeForm"
          :formData="formData"
        ></editForm>
      </div>
    </dialogPublic>
  </div>
</template>

<script>
import {
  getWorkflow,
  submitWorkflow,
  getWorkflowOnly,
  getWorkflowInit,
  getNextHandler,
  getFilterMember,
} from "@/api/common";
import _ from "lodash"; //抖动函数，一定时间内多次点击只执行最后一次
import workFlowMember from "../memberSelect/workFlowMember.vue";

export default {
  components: { workFlowMember },
  props: {
    //工作流编码
    workflowCode: {
      type: String,
      default: "",
    },
    //当前流程信息
    currentFlowData: {
      type: Object,
      default: function() {
        return {};
      },
    },
    //是否初始化流程
    isInit:{
      type: Boolean,
      default: false,
    },
    //工作流参数
    workParams: {
      type: Object,
      default: () => {
        return {};
      },
    },
    //提交前回调函数
    beforeSubmit: {
      type: Object,
      default: function() {
        return {};
      },
    },
    //是否是详情不可操作
    isDetails: {
      type: Boolean,
      default: false,
    },
    //提交前校验信息
    beforeFlowSubmit: {
      type: Object,
      default: function() {
        return {};
      },
    },
    //提交前校验失败提示信息
    beforeFlowSubmitErr: {
      type: String,
      default: "",
    },
    //驳回节点是否默认为空
    rejectCodeNull:{
      type: Boolean,
      default: false,
    }
  },
  data() {
    return {
      commitParam: null,
      timer: null,
      showDetail: false,
      showMember: false,
      iframeUrl: "", //iframeUrl
      nodeKey: "", //标签节点key,用于操作流程上的node
      inputId: "", //标签节点id，用于操作流程上的node
      showDialog: false,
      orgMemberSelect: {},
      //人员选择时对应节点和人员对象
      checkNodeObj: {},
      //下个节点人员
      nextLeaderCode: {},
      artificialDecisionCondition: "", //下步执行
      communicateUser: "", //沟通人员
      billId: "", //流程id
      relatedUser: "", //转办人信息
      formConfig: {
        labelWidth: "120px",
        itemArr: [
          {
            label: "下一步处理人:",
            prop: "name",
            type: "textarea",
            disabled: true,
            span: 23,
            rows: 6,
          },
        ],
      },
      //弹出框表单数据
      formData: {
        name: "",
      },
    };
  },
  created() {
    this.initIframe();
  },
  mounted() {
    // this.getFlowInfo();
    window.addEventListener("message", this.workflowReceiveMessage);
  },
  beforeDestroy() {
    window.removeEventListener("message", this.workflowReceiveMessage);
  },
  methods: {
    //初始化iframe
    initIframe() {
      let { id } = this.currentFlowData;
      // if (this.workflowCode != "") {
      //   this.billId = this.workflowCode;
      // } else {
      //   this.billId = id;
      // }
      if (!this.isInit) {
        this.billId = id;
      }
      // 开始修改
      // 结束修改
      sessionStorage.setItem("workflowMember", JSON.stringify({}));
      let randomNum = Math.floor(Math.random() * 100000); //取随机数，防止IE缓存
      this.iframeUrl = `/static/workflow/workflow.html?${randomNum}`;
    },
    commitAll() {
      submitWorkflow(this.commitParam).then((res) => {
        this.orgMemberSelect.chosedData = [];
        this.showDetail = false;
        this.$message.success("流程提交成功！");
        sessionStorage.setItem("workflowMember", JSON.stringify({}));
        this.$emit("submitSuccess", true);
      });
    },
    // 监听回调
    workflowReceiveMessage(event) {
      // 根据上面制定的结构来解析iframe内部发回来的数据
      const data = event.data;
      switch (data.cmd) {
        case "height":
          this.setIframeHeight(data.params.height);
          break;
        /**点击提交流程时回调 */
        case "callBackSubmit":
          this.throttle(this.submitFlow, 3000)(data.params.data);
          // this.submitFlow(data.params.data);
          break;
        /**选择人员 */
        case "memberdialog":
          this.setIframemember(data.params);
          break;
        /**获取流程数据 */
        case "loadSure":
          this.getFlowInfo();
          break;
        // 通知子页面已经完成更新
        case "loadDone":
          const ref = document.querySelector('#workflow');
          this.$emit('getRefByWorkFlow', ref);
          break;
      }
    },

    // 开始修改
    // 获取流程图信息,并给子组件赋值html
    async getFlowInfo() {
      let res = {};
      if (this.isDetails) {
        res = await getWorkflowOnly(this.billId);
      } else {
        let data = {
          findId: this.billId,
          processCode: this.workflowCode,
        };
        data.variable = JSON.stringify(this.workParams);
        res = await getWorkflow(data);
      }
      this.$nextTick(() => {
        if (this.isDetails && myOnlyViewFrame) {
          myOnlyViewFrame.window.setFlowHtml(res.data);
        }
        if (!this.isDetails && myFrame) {
          // res.data=res.data.replace("data= submitCheck(data)","debugger;\n data= submitCheck(data)")
          //工作票不显示 驳回 返回本节点
          let flag = this.workflowCode.indexOf("ticket_work_status");
          if (flag != -1) {
            res.data = res.data.replace(
              'id="rejectType"',
              'style="display: none"'
            );
            res.data = res.data.replace("返回本节点", "");
          }
          myFrame.window.setFlowHtml(res.data,this.rejectCodeNull);
        }
      });
      // 结束修改
    },
    throttle(fn, wait) {
      let that = this;
      return function() {
        if (that.timer) {
          return;
        } else {
          fn.call(this, arguments);
          that.timer = setTimeout(() => {
            // 此处设置apply 是为了保证函数上下文不改变
            clearTimeout(that.timer);
            that.timer = null;
          }, wait);
        }
      };
    },

    // 抖动函数，可再次处理业务数据，先提交确认信息
    toSubmintFlow: _.debounce((data) => {
      // this.submitFlow(data);
      this.throttle(this.submitFlow, 3000)(data);
    }, 200),
    // 提交工作流
    submitFlow() {
      let data = arguments[0][0];
      if (this.beforeFlowSubmit.hasOwnProperty("methods")) {
        let value = this.beforeFlowSubmit.methods(data);
        value
          .then((res) => {
            if (res) {
              this.toSubmitFlow(data);
            }
          })
          .catch((err) => {
            // 根据业务设置beforeFlowSubmitErr显示提示信息
            if (this.beforeFlowSubmitErr) {
              this.$message.warning(this.beforeFlowSubmitErr);
            }
          });
      } else {
        this.toSubmitFlow(data);
      }
    },
    toSubmitFlows(data) {
      this.toSubmitFlow(data);
    },
    async toSubmitFlow(data) {
      try {
        let beforConditions = true;
      if (this.beforeSubmit.hasOwnProperty("methods")) {
        beforConditions = await this.beforeSubmit.methods(data);
      }
      if (["2", "4"].includes(data.operation)) {
        //转办
        data.relatedUser = this.relatedUser;
      }
      if (data.operation == "128") {
        //取消沟通
        var wfHtml = document.getElementById("workflow").contentDocument;
        let node = wfHtml
          .getElementsByClassName("add_communication-box")[0]
          .getElementsByClassName("icon-check");
        let cancelName = [];
        if (node) {
          for (let i = 0; i < node.length; i++) {
            let name = node[i].getAttribute("data-code");
            cancelName.push(name);
          }
          data.relatedUser = cancelName.join();
        }
      }
      if (data.operation == "1") {
        //驳回节点
        var wfHtml = document.getElementById("workflow").contentDocument;
        let selectValue = wfHtml.getElementById("reback") || {};
        let checkValue = wfHtml.getElementById("rejectType") || {};
        this.rejectNodeCode = selectValue.value || -1; //驳回节点名称
        this.rejectType = checkValue.checked ? 1 : 0;
        data.rejectNodeCode = this.rejectNodeCode;
        data.rejectType = this.rejectType;
      }
      let dataArr = null;
      let { id } = this.currentFlowData;
      data.dataId = id;
      data.formVariables = JSON.stringify(this.currentFlowData); //表单数据
      data.dataCode = this.currentFlowData.code;
      data.dataTitle =
        this.currentFlowData.title || this.currentFlowData.name || "";
      this.commitParam = data;
      if (data.operation == "32") {
        //下一个审批人
        var wfHtml = document.getElementById("workflow").contentDocument;
        let nextPerson = wfHtml.getElementById("artificialDecision") || "";
        this.artificialDecisionCondition = nextPerson ? nextPerson.value : null;
        data.artificialDecisionCondition = this.artificialDecisionCondition;
        let node =
          wfHtml.getElementsByClassName("m-node-operator")[0] ||
          wfHtml.getElementsByClassName("node-operator")[0];
        if (node) {
          // let nodeKey = node.getAttribute("data-node");
          data.otherNodeCandidates = JSON.stringify(this.nextLeaderCode);
        }
        let nodeCode = wfHtml.getElementsByTagName("currnodecode")[0].innerHTML;
        data.nodeCode = nodeCode;
        data.nextNodeCode = data.artificialDecisionCondition;
        let params = null;
        getNextHandler(data)
          .then(
            (res) => {
              if (res.code == 200) {
                dataArr = res.data;
                if (dataArr == null || dataArr == undefined) {
                  this.noDialogCommit(data);
                }
                let nameStr = "";
                let accountStr = [];
                if (dataArr && dataArr.length > 0) {
                  dataArr.map((item) => {
                    nameStr += item.name + ",";
                    accountStr += item.account + ",";
                  });
                  //去掉最后一个的逗号
                  if (nameStr && nameStr.length > 0) {
                    nameStr = nameStr.substr(0, nameStr.length - 1);
                  }
                  if (accountStr && accountStr.length > 0) {
                    accountStr = accountStr.substr(0, accountStr.length - 1);
                  }
                  params = JSON.parse(data.formVariables);
                  params.EAM_USER = accountStr;
                  data.formVariables = JSON.stringify(params);
                  this.commitParam = data;
                  this.formData.name = nameStr;
                  this.showDetail = true;
                }
              }
            },
            (error) => {
              //this.$message.error(error);
            }
          )
          .catch((error) => {
            this.$message.error(error);
            throw error;
          });
      }
      if (data.operation != "32") {
        this.noDialogCommit(data);
      }
      } catch (error) {
        
      }
      
    },
    noDialogCommit(data) {
      let params = JSON.parse(data.formVariables);
      if (data.operation == '1') {
        delete params.EAM_USER
      } else {
        params.EAM_USER = "";
      }
      data.formVariables = JSON.stringify(params);
      this.showDetail = false;
      submitWorkflow(data).then((res) => {
        this.orgMemberSelect.chosedData = [];
        this.$message.success("流程提交成功！");
        sessionStorage.setItem("workflowMember", JSON.stringify({}));
        this.$emit("submitSuccess", true);
      }).catch((err) => {
        throw err;
      });
    },
    //获取待审数量
    getFlowCount() {
      // this.$store.dispatch("GetFlowInfoCount");
    },
    //点击节点选择人员时
    async setIframemember(data) {
      this.inputId = data.data;
      this.nodeKey = data.inputId;
      let workflowMember =
        JSON.parse(sessionStorage.getItem("workflowMember")) || [];
      if (["transfer", "communicate"].includes(this.nodeKey)) {
        this.orgMemberSelect = {
          chosedData: workflowMember[this.nodeKey],
          type: "user-select",
          multiple: true, //单选还是多选
          outOrg: "", //是否是外单位
          level: null,
          defaultOrg: "",
          permission: true,
        };
        this.showDialog = true;
      } else {
        let param = {
          processCode: this.workflowCode,
          dataNode: data.inputId,
          formVariables: JSON.stringify(this.currentFlowData),
        };
        let res = await getFilterMember(param);
        if (res.data) {
          this.orgMemberSelect = {
            chosedData: workflowMember[this.nodeKey] || [],
            tableData: res.data,
          };
          this.showMember = true;
        } else {
          this.orgMemberSelect = {
            chosedData: workflowMember[this.nodeKey],
            type: "user-select",
            multiple: true, //单选还是多选
            outOrg: "", //是否是外单位
            level: null,
            defaultOrg: "",
            permission: true,
          };
          this.showDialog = true;
        }
      }
    },
    //确定选择人员
    addSeleteMember() {
      let data = this.$refs.newMember.getSelectData();
      let workflowMember =
        JSON.parse(sessionStorage.getItem("workflowMember")) || {};
      workflowMember[this.nodeKey] = data;
      sessionStorage.setItem("workflowMember", JSON.stringify(workflowMember));
      let names = [];
      let ids = [];
      let loginName = []; //人员登录账号信息
      if (data) {
        data.map((i) => {
          i.code = i.loginId;
          names.push(i.name);
          ids.push(i.id);
          loginName.push(i.account);
        });
      }
      var wfHtml = document.getElementById("workflow").contentDocument;
      let inputArr = wfHtml.getElementsByTagName("input");
      for (var i = 0; i < inputArr.length; i++) {
        if (
          ["节点处理人", "请输入沟通人员", "请输入转办人员"].includes(
            inputArr[i].getAttribute("placeholder")
          )
        ) {
          let node = inputArr[i].getAttribute("data-node") || null;
          if (node == this.nodeKey) {
            inputArr[i].value = names.join();
            this.nextLeaderCode[this.nodeKey] = loginName.join();
            inputArr[i].dataset.code = loginName.join(); //给input设置code属性
          }
        }
      }
      this.relatedUser = loginName.join();
      this.showDialog = false;
      this.showMember = false;
    },
  },
};
</script>

<style lang="less">
.work-flow {
  height: 100%;
  .work-flow__iframe {
    height: 100%;
    min-height: 800px;
    padding: 10px;
  }
}
.nextNode {
  padding-top: 23px;
}
</style>
